package com.innovation.chengzhangriji.ui;

import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DiscoverGalleryActivity extends BaseActivity {
    private Bitmap image;
    private String[] photoUrls;
    private AlertDialog alertDialog;
    private ViewPager viewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int index = getIntent().getIntExtra("index", 0);
        photoUrls = getIntent().getStringArrayExtra("photoUrls");
        setContentView(R.layout.activity_discover_gallery);
        viewPager = (ViewPager) findViewById(R.id.pager);
        viewPager.setAdapter(new DiscoverGalleryAdapter());
        viewPager.setCurrentItem(index);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        finish();
        return true;
    }

    private class DiscoverGalleryAdapter extends PagerAdapter implements ImageLoadingListener, ImageLoadingProgressListener {

        private ImageView[] imageThumbnails;

        private ImageView[] imagePhotos;

        public DiscoverGalleryAdapter() {
            imageThumbnails = new ImageView[photoUrls.length];
            imagePhotos = new ImageView[photoUrls.length];
        }

        @Override
        public int getCount() {
            if (photoUrls == null) {
                return 0;
            }
            return photoUrls.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = LayoutInflater.from(container.getContext()).inflate(R.layout.item_discover_photo_gallery, container, false);
            imageThumbnails[position] = (ImageView) view.findViewById(R.id.image_thumbnail);
            imagePhotos[position] = (ImageView) view.findViewById(R.id.image_photo);
            if(photoUrls[position].startsWith("/")) {
                ImageLoader.getInstance().displayImage("file://" + photoUrls[position], imagePhotos[position], Config.getOptionsGallery(), this, this);
            } else {
                ImageLoader.getInstance().displayImage(Config.createSizeUrl(photoUrls[position], 480), imageThumbnails[position], Config.getOptionsPhoto());
                ImageLoader.getInstance().displayImage(photoUrls[position], imagePhotos[position], Config.getOptionsGallery(), this, this);
            }
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
            view.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    final ImageView iv = new ImageView(DiscoverGalleryActivity.this);
                    ImageLoader.getInstance().displayImage(photoUrls[viewPager.getCurrentItem()], iv, Config.getOptionsGallery(), null);
                    alertDialog = new AlertDialog.Builder(DiscoverGalleryActivity.this).create();
                    alertDialog.show();
                    alertDialog.getWindow().setGravity(Gravity.BOTTOM);
                    alertDialog.getWindow().setContentView(R.layout.dialog_savephoto);
                    alertDialog.getWindow()
                            .findViewById(R.id.tv_phote_cancle)
                            .setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    alertDialog.dismiss();
                                }
                            });
                    alertDialog.getWindow()
                            .findViewById(R.id.tv_phote_save)
                            .setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    image = ((BitmapDrawable) iv.getDrawable()).getBitmap();
                                    Log.d("2asd", "" + image);
                                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    String date = df.format(new Date());
                                    date = date.substring(0, 4) + date.substring(5, 7) + date.substring(8, 10) + "_" + date.substring(11, 13) + date.substring(14, 16) + date.substring(17, 19);
                                    String nowdate = Environment.getExternalStorageDirectory() + "/DCIM/Camera/" + date + ".jpg";
                                    try {
                                        File myCaptureFile = new File(nowdate);
                                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                                        image.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                                        bos.flush();
                                        bos.close();
                                    } catch (Exception e) {

                                    }
                                    alertDialog.dismiss();
                                    tipShow("已保存到系统相册");

                                }
                            });
                    return false;
                }
            });
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View)object);
        }

        @Override
        public void onLoadingStarted(String imageUri, View view) {

        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            for (int i = 0; i < photoUrls.length; i++) {
                if (photoUrls[i].equals(imageUri)) {
                    if(imageThumbnails[i] != null) {
                        imageThumbnails[i].setVisibility(View.GONE);
                    }
                }
            }
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {

        }

        @Override
        public void onProgressUpdate(String imageUri, View view, int current, int total) {

        }

    }

}
